package com.game.message.jpb;


import com.baidu.bjf.remoting.protobuf.Codec;
import com.baidu.bjf.remoting.protobuf.ProtobufProxy;
import com.game.message.Msg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * biadu protobuf工具类封装
 */
public class JPbUtil {
    private static Logger logger = LoggerFactory.getLogger(JPbUtil.class);
    public static <T> byte[] getBytes(Class<T> cls, T t) throws Exception {
        Codec<T> codec = ProtobufProxy.create(cls);
        byte[] encode = codec.encode(t);
        return encode;
    }

    public static <T> String getString(Class<T> cls, T t) throws Exception {
        Codec<T> codec = ProtobufProxy.create(cls);
        byte[] encode = codec.encode(t);
        return new String(encode);
    }

    public static <T> T getPb(Class<T> cls, byte[] data) throws Exception {
        Codec<T> codec = ProtobufProxy.create(cls);
        if (data == null) {
            T t = cls.newInstance();
            return t;
        }
        T t = codec.decode(data);
        return t;
    }

    public static <T> T getPb(Class<T> cls, String data) throws Exception {
        Codec<T> codec = ProtobufProxy.create(cls);
        if (data == null) {
            T t = cls.newInstance();
            return t;
        }
        T t = codec.decode(data.getBytes());
        return t;
    }

    public static <T extends SuperJPB> Msg getMsg(Class<T> cls, T t) {
        Msg msg = new Msg();
        try {
            byte[] bytes = getBytes(cls, t);
            msg.setMsgId(t.getMsgId());
            msg.setBody(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

    public static <T extends SuperJPB> T getPb(Class<T> cls, Msg msg) {
        Codec<T> codec = ProtobufProxy.create(cls);
        byte[] data = msg.getBody();
        T t = null;
        if (data == null) {
            try {
                t = cls.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            return t;
        }
        try {
            t = codec.decode(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
        t.setMsgId(msg.getMsgId());
        t.setUserId(msg.getUserId());
        return t;
    }
}
